<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2022/3/16
 */

namespace App\Services;

use App\Http\Controllers\InfoController;
use App\Http\Controllers\InfoPageController;
use App\Models\InfoCategory;
use Illuminate\Support\Facades\Route;

/**
 * 信息栏目分类模块服务层
 *
 * Class InfoCategoryService
 * @package App\Services
 */
class InfoCategoryService
{

    /**
     * 获取所有栏目
     * @return mixed
     */
    public static function getAllList()
    {
        $result = CacheService::getCache('infoCategoryServiceCache');
        if ($result == null) {
            $where = [['status', 1]];
            $result = InfoCategory::where($where)->orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
            collect($result)->each(function (&$item) {
                // link
                self::setCateLink($item);
            });
            CacheService::setCache('infoCategoryServiceCache', $result);
        }
        return $result;
    }

    /**
     * 获取栏目树
     * @return array
     */
    public static function getTree()
    {
        $getAllList = self::getAllList();
        return TreeService::make($getAllList);
    }

    /**
     * 获取所有子栏目树
     * @param int $parent_id // 父类ID
     * @return mixed
     */
    public static function getAllSubsTreeByParentId($parent_id = 0)
    {
        return TreeService::getSubsTreeByParentId(self::getAllList(), $parent_id);
    }

    /**
     * 获取所有子栏目ID集
     * @param int $parent_id // 父类ID
     * @return array|int[]
     */
    static function getSubIdsByParentId($parent_id = 0)
    {
        return TreeService::getSubIdsByParentId(self::getAllList(), $parent_id);
    }

    /**
     * 根据指定栏目ID获取所有父级ID集
     */
    static function getParentIdsById($cate_id = 0)
    {
        if (!$cate_id) return [];
        return TreeService::getParentIdsById(self::getAllList(), $cate_id);
    }

    /**
     * 根据栏目ID获取指定栏目详情
     * @param int $cate_id
     * @return array|mixed
     */
    public static function getDetail($cate_id = 0)
    {
        $getAllList = self::getAllList();
        if (!$cate_id || !$getAllList) return [];
        $result = collect($getAllList)->first(function ($value, $key) use ($cate_id) {
            return $value['id'] == $cate_id;
        });
        return $result ?: [];
    }


    /**
     * 根据栏目英文标识获取指定栏目详情
     * @param int $enname // 英文名称标识
     * @return array|mixed
     */
    public static function getDetailByEnName($enname = 0)
    {
        $getAllList = self::getAllList();
        if (!$enname || !$getAllList) return [];
        $result = collect($getAllList)->first(function ($value, $key) use ($enname) {
            return $value['enname'] == $enname;
        });
        return $result ?: [];
    }

    /**
     * 根据栏目项获取栏目访问链接
     * @param $item
     * @return string
     * 栏目链接规则：
     *   1.栏目频道：/channel/栏目ID.html，例：/channel/1.html；
     *   2.列表栏目：/list/栏目ID.html，例：/list/1.html；
     *   3.单页栏目：/page/栏目ID.html，例：/page/1.html 。
     */
    static function getHref($item)
    {
        $href = "";
        $enname = str_replace(' ', '', $item->enname);
        if ($item) {
            switch ($item->type) {
                case 1: // 频道
                    $name = $enname ?: 'channel';
                    $index_template = trim($item->index_template);
                    if (!empty($index_template)) {
                        $href = "/${name}/" . $item->id . ".html";
                    }
                    break;
                case 2: // （文章、图集）列表功能
                    $name = $enname ?: 'list';
                    $href = "/${name}/" . $item->id . ".html";
                    break;
                case 3:// 单页
                    $name = $enname ?: 'page';
                    $href = "/${name}/" . $item->id . ".html";
                    break;
                case 4: // 外链
                    $href = $item->href ?: $href;
                    break;
            }
        }
        return $item->type != 4 && !empty($href) ? url($href) : $href;
    }

    /**
     * 根据栏目项获取栏目路由规则
     * @param $item
     * @return string
     * 说明：
     * 1.栏目需填写英文名称(英文/拼音)，规则才生效
     * 2.若执行php artisan route:cache生成路由缓存，本地需执行php artisan redis:subscribe订阅更新缓存通道，后台清除缓存时将通知前台更新路由规则生效，线上部署建议进程守护
     * 3.若未生成路由缓存，后台清除缓存时路由规则将及时生效
     */
    static function getSeoRoute($item)
    {
        $route = "";
        $enname = str_replace(' ', '', $item->enname);
        if ($enname) {
            switch ($item->type) {
                case 1: // 频道
                    $index_template = trim($item->index_template);
                    if (!empty($index_template)) {
                        $route = "${enname}/" . '{cate}.html';
                    }
                    break;
                case 2: // （文章、图集）列表功能*
                    $route = "${enname}/" . '{cate}.html';
                    break;
                case 3:// 单页
                    $route = "${enname}/" . '{cate}.html';
                    break;
                default: // 外链
                    break;
            }
        }
        return $route;
    }

    /**
     * 生成栏目路由
     */
    static function makeSeoRoute()
    {
        $getAllCate = self::getAllList();
        $cateRouteList = [];
        collect($getAllCate)->each(function ($item) use (&$cateRouteList) {
            if ($item['route'] && in_array($item->type, [1, 2, 3])) {
                $actions = [
                    1 => [InfoController::class, 'index'], // 频道
                    2 => [InfoController::class, 'list'], // 列表功能
                    3 => [InfoPageController::class, 'index'] // 单页
                ];
                @$action = $actions[$item->type];
                if (!in_array($item['route'], $cateRouteList) && isset($action)) {
                    $cateRouteList[] = $item['route'];
                    $enname = str_replace(' ', '', $item->enname);
                    Route::get($item['route'], $action)->name($enname . $item['id']);
                    // 生成列表功能栏目的详情页seo路由
                    if ($item['type'] == 2) {
                        Route::get($enname . '/{cate}.{info}.html', [InfoController::class, 'show'])->name($enname . 'show' . $item['id']);
                    }
                }
            }
        });
    }


    /**
     * 根据栏目ID获取所有父级栏目数据
     * @param int $id
     * @return array
     */
    static function getAllParentsById($id = 0)
    {
        if (!$id) return [];
        $allCate = self::getAllList();
        return TreeService::getAllParentsById($allCate, $id);
    }

    /**
     * 获取当前栏目面包屑
     * @param InfoCategory $cate
     * @return InfoCategory[]|array
     */
    static function getBreadcrumb(InfoCategory $cate)
    {
        // link
        $href = self::getHref($cate);
        $currentCate = [
            'title' => $cate->name,
            'href_' => $href ? " href =${href} " : '',
            'href_target_' => $cate->href_target ? " target =$cate->href_target " : '',
            'rel_' => $cate->rel ? " rel =$cate->rel " : ''
        ];
        $data = [$currentCate];
        $allCate = self::getAllList();
        $getAllParentsById = TreeService::getAllParentsById($allCate, $cate->id);
        if ($getAllParentsById) {
            $getAllParentsById = collect($getAllParentsById)->reverse()->values()->all();
            $getAllParentsById = collect($getAllParentsById)->map(function ($item) {
                return [
                    'title' => $item['name'],
                    'href_' => $item['href_'],
                    'href_target_' => $item['href_target_'],
                    'rel_' => $item['rel_'],
                ];
            })->toArray();
            $data = array_merge($getAllParentsById, $data);
        }
        return $data;
    }

    /**
     * 设置栏目链接相关属性
     * @param $item
     */
    static function setCateLink(&$item = null)
    {
        if ($item != null) {
            $item['route'] = self::getSeoRoute($item);
            $item['href'] = self::getHref($item);
            $item['href_'] = $item['href'] ? " href =${item['href']} " : '';
            $item['href_target_'] = $item->href_target ? " target =$item->href_target " : '';
            $item['rel_'] = $item->rel ? " rel =$item->rel " : '';
        }
    }


}
